from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc

from app.core.database import get_async_session
from app.schemas.meeting import Meeting, MeetingCreate, MeetingUpdate, MeetingList, MeetingWithDetails
from app.models.meeting import Meeting as MeetingModel, MeetingStatus
from app.models.user import User as UserModel

router = APIRouter()


@router.post("/", response_model=Meeting)
async def create_meeting(
    meeting: MeetingCreate,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """创建新会议"""
    db_meeting = MeetingModel(
        **meeting.dict(),
        user_id=current_user.id if current_user else 1,  # 临时使用固定用户ID
        status=MeetingStatus.RECORDING
    )
    db.add(db_meeting)
    await db.commit()
    await db.refresh(db_meeting)
    return db_meeting


@router.get("/", response_model=MeetingList)
async def get_meetings(
    page: int = Query(1, ge=1),
    size: int = Query(10, ge=1, le=100),
    status: Optional[MeetingStatus] = Query(None),
    search: Optional[str] = Query(None),
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """获取会议列表"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 构建查询
    query = select(MeetingModel).where(MeetingModel.user_id == user_id)

    # 状态过滤
    if status:
        query = query.where(MeetingModel.status == status)

    # 搜索过滤
    if search:
        query = query.where(
            MeetingModel.title.ilike(f"%{search}%")
        )

    # 计算总数
    count_query = select(func.count()).select_from(query.subquery())
    total_result = await db.execute(count_query)
    total = total_result.scalar()

    # 分页和排序
    query = query.order_by(desc(MeetingModel.created_at))
    query = query.offset((page - 1) * size).limit(size)

    result = await db.execute(query)
    meetings = result.scalars().all()

    # 构建带详细信息的会议列表
    meetings_with_details = []
    for meeting in meetings:
        # 获取转录数量
        transcript_count_query = select(func.count()).select_from(
            select(MeetingModel.transcripts).where(MeetingModel.id == meeting.id).subquery()
        )
        transcript_count_result = await db.execute(transcript_count_query)
        transcript_count = transcript_count_result.scalar() or 0

        # 检查是否有纪要
        has_minutes = bool(meeting.minutes)
        minutes_status = meeting.minutes.status if meeting.minutes else None

        meetings_with_details.append(MeetingWithDetails(
            **meeting.__dict__,
            transcript_count=transcript_count,
            has_minutes=has_minutes,
            minutes_status=minutes_status
        ))

    pages = (total + size - 1) // size

    return MeetingList(
        meetings=meetings_with_details,
        total=total,
        page=page,
        size=size,
        pages=pages
    )


@router.get("/{meeting_id}", response_model=Meeting)
async def get_meeting(
    meeting_id: int,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """获取单个会议详情"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    result = await db.execute(query)
    meeting = result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    return meeting


@router.put("/{meeting_id}", response_model=Meeting)
async def update_meeting(
    meeting_id: int,
    meeting_update: MeetingUpdate,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """更新会议信息"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 获取会议
    query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    result = await db.execute(query)
    meeting = result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    # 更新字段
    update_data = meeting_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(meeting, field, value)

    await db.commit()
    await db.refresh(meeting)
    return meeting


@router.delete("/{meeting_id}")
async def delete_meeting(
    meeting_id: int,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """删除会议"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 获取会议
    query = select(MeetingModel).where(
        MeetingModel.id == meeting_id,
        MeetingModel.user_id == user_id
    )
    result = await db.execute(query)
    meeting = result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    await db.delete(meeting)
    await db.commit()
    return {"message": "会议已删除"}